import threading
import socketserver
import logging

FORMAT = "%(asctime)s %(threadName)s %(thread)d %(message)s"
logging.basicConfig(format=FORMAT, level=logging.INFO)


class MyHandler(socketserver.StreamRequestHandler):
    def setup(self,clients = set(),lock = threading.Lock()):
        super().setup()
        self.event = threading.Event()
        self.clients = clients
        self.lock = lock

    def finish(self):
        super().finish()
        self.event.set()

    def handle(self):
        super().handle() # 可以不调用，父类handle什么都没有做
        while not self.event.is_set():
            with self.lock:
                self.clients.add(self)
            print(self.clients)
            data = self.rfile.readline().decode()
            msg = data.strip()
            if msg == 'quit' or msg == '':
                with self.lock:
                    self.clients.remove(self)
                self.finish()
                break
            print(msg)
            with self.lock:
                for client in self.clients:
                    client.wfile.write(msg.encode())
        logging.info('{} quit'.format(self.request))

addr = ('127.0.0.1', 9999)
server = socketserver.ThreadingTCPServer(addr, MyHandler)# 注意参数是MyHandler类
print(server)
threading.Thread(target=server.serve_forever,name='EchoServer',daemon=True).start()
#server.handle_request() # 一次性
server.daemon_threads = True
while True:
    cmd = input('>>')
    if cmd == 'quit':
        server.server_close()
        break
    print(threading.enumerate())
